from django.shortcuts import render
from django.views.decorators.http import require_GET, require_POST
from django.core.paginator import Paginator
from django.db.models import Q
from django.http import JsonResponse

from apps.base.models import Log
from service import res_json_data


@require_GET
def get_list_as_table(request):
    """获取日志列表数据"""
    # 接收请求参数
    page = request.GET.get('page', 1)
    limit = request.GET.get('limit', 10)

    user = request.GET.get('user', '')  # 操作者
    action = request.GET.get('action', '')  # 操作类型
    model_name = request.GET.get('model_name', '')  # 操作表
    status = request.GET.get('status', '')  # HTTP状态码
    start_time = request.GET.get('start_time', '')  # 开始时间
    end_time = request.GET.get('end_time', '')  # 结束时间

    queryset = Log.objects.filter()
    if user:
        queryset = queryset.filter(user__icontains=user)
    if status:
        queryset = queryset.filter(status=status)
    if action:
        queryset = queryset.filter(action=action)
    if model_name:
        queryset = queryset.filter(model_name__icontains=model_name)
    if start_time and end_time:
        queryset = queryset.filter(create_datetime__gte=start_time, create_datetime__lte=end_time)

    queryset_page = queryset[(int(page) - 1) * int(limit): int(page) * int(limit)]

    res_data = []
    for item in queryset_page:
        item_data = item.json()
        res_data.append(item_data)

    return res_json_data.table_api(data=res_data, count=len(queryset))


# /api/v1/log/del/
@require_POST
def log_del(request):
    """删除日志"""
    del_id = request.POST.get('id')
    log_obj = Log.objects.filter(id=del_id).first()
    if not log_obj:
        return res_json_data.not_found_api(msg="日志不存在!")
    log_obj.delete()  # 物理删除
    return res_json_data.success_api(msg='日志删除成功!')
